#lang racket

(provide match-assoc)

;; > (import (match-assoc))
;; > (match-assoc '((x . 3) (y . 5) (z . 7)) (x z) (list x z))
;; (3 7)
;; > (match-assoc '((x . 3) (y . 5) (z . 7)) (x z h) (list x z))
;; Exception in match-assoc: the assoc list was missing a key with irritant (((x . 3) (y . 5) (z . 7)) h)
;; Type (debug) to enter the debugger.

(define-syntax match-assoc
  (syntax-rules ()
    ((match-assoc <thing> (<var> ...) <body> ...)
     (let ((thing <thing>)) (match-assoc* thing (<var> ...) <body> ...)))))

(define-syntax match-assoc*
  (syntax-rules ()
    ((match-assoc* <thing> () <body> ...)
     (begin <body> ...))
    ((match-assoc* <thing> (<var0> <var> ...) <body> ...)
     (cond ((assoc '<var0> <thing>)
            => (lambda (entry)
		 ;(when (not (pair? entry))
		 ;  (error 'match-assoc "Not a pair" entry))
                 (let ((<var0> (cdr entry)))
                   (match-assoc* <thing> (<var> ...) <body> ...))))
           (else (error 'match-assoc "the assoc list was missing a key" (list <thing> '<var0>)))))))
